package com.wk.warehouse.filter;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.wk.warehouse.controller.LoginController;
import com.wk.warehouse.entity.Result;
import com.wk.warehouse.util.WarehouseConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter("/*")
@Slf4j
public class SecurityFilter implements Filter {

    @Autowired
    private LoginController loginController;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info(this.getClass().getName() + "：初始化了！");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        String path = request.getServletPath();
        System.out.println("path:" + path);

        // 白名单
        if(path.equals("/user/login") || path.equals("/user/logout")){
            // 继续传递
            chain.doFilter(request, response);
            return;
        }

        // 检查Token
        String clientToken = request.getHeader(WarehouseConstants.HEADER_TOKEN_NAME);
        Result result = loginController.verifyToken(clientToken);
        if(result.isSuccess()){
            // 校验通过
            chain.doFilter(request, response);
            return;
        }
        // 其它情况，将校验结果返回
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(result); // 将result对象转成json串
        out.print(json);
        out.flush();
        out.close();
    }

    @Override
    public void destroy() {

    }
}
